package com.only4play.portal.cp.bean.message.xmlmessage;

import com.fasterxml.jackson.core.JacksonException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.only4play.portal.cp.config.CpConfigStorage;
import lombok.Getter;
import lombok.Setter;

import java.io.Serializable;
import java.util.HashMap;

/**
 * @author liyuncong
 * @version 1.0
 * @file PortalCpXmlMessage
 * @brief PortalCpXmlMessage
 * @details PortalCpXmlMessage
 * @date 2024-06-07
 *
 * Edit History
 * ----------------------------------------------------------------------------
 * DATE                     NAME               DESCRIPTION
 * 2024-06-07               liyuncong          Created
 */
@Getter
@Setter
public class CpXmlMessage implements Serializable {

    private String agentId;

    private String fromUserName;

    private String toUserName;

    private Long createAt;

    private String msgType;

    private String content;

    private Long msgId;

    private String event;

    private String eventKey;


    public static CpXmlMessage fromEncryptedXml(
        String encryptedXml,
        CpConfigStorage portalCpConfigStorage,
        String timestamp,
        String nonce,
        String msgSignature
    ) {
        // todo 原始报文解密
        return fromXml(encryptedXml);
    }

    protected static CpXmlMessage fromXml(String xml) {
        final CpXmlMessage xmlMessage = new CpXmlMessage();
        // 模拟解析xml
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            HashMap hashMap = objectMapper.readValue(xml, HashMap.class);
            xmlMessage.setAgentId((String) hashMap.get("agentId"));
            xmlMessage.setFromUserName((String) hashMap.get("fromUserName"));
            xmlMessage.setToUserName((String) hashMap.get("toUserName"));
            xmlMessage.setCreateAt((Long) hashMap.get("createAt"));
            xmlMessage.setMsgType((String) hashMap.get("msgType"));
            xmlMessage.setContent((String) hashMap.get("content"));
            xmlMessage.setMsgId((Long) hashMap.get("msgId"));
            xmlMessage.setEvent((String) hashMap.get("event"));
            xmlMessage.setEventKey((String) hashMap.get("eventKey"));

        } catch (JacksonException exception) {
            return xmlMessage;
        }

        return xmlMessage;
    }
}
